package ch.kerbtier.webglue;

import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
import groovy.util.ResourceException;
import groovy.util.ScriptException;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class GlueSessionListener implements HttpSessionListener{

	public void sessionCreated(HttpSessionEvent hse) {
		final GroovyScriptEngine engine = (GroovyScriptEngine)hse.getSession().getServletContext().getAttribute("glue_groovy_engine");
        final Binding binding = new Binding();
        
        binding.setVariable("servletContext", hse.getSession().getServletContext());
        binding.setVariable("context", hse.getSession().getServletContext());
        binding.setVariable("session", hse.getSession());
		binding.setVariable("script", new Object() {
			public Object evaluate(String name) {
				try {
					return engine.run(name, binding);
				} catch (ResourceException e) {
					e.printStackTrace();
				} catch (ScriptException e) {
					e.printStackTrace();
				} catch (Throwable e) {
					e.printStackTrace();
				}
				return null;
			}

		});
        
        try {
            engine.run("sessionCreated.groovy", binding);
        } catch (ResourceException e) {
            e.printStackTrace();
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch(Throwable e){
            e.printStackTrace();
        }
		
	}

	public void sessionDestroyed(HttpSessionEvent hse) {
		final GroovyScriptEngine engine = (GroovyScriptEngine)hse.getSession().getServletContext().getAttribute("glue_groovy_engine");
        final Binding binding = new Binding();
        
        binding.setVariable("servletContext", hse.getSession().getServletContext());
        binding.setVariable("context", hse.getSession().getServletContext());
        binding.setVariable("session", hse.getSession());
		binding.setVariable("script", new Object() {
			public Object evaluate(String name) {
				try {
					return engine.run(name, binding);
				} catch (ResourceException e) {
					e.printStackTrace();
				} catch (ScriptException e) {
					e.printStackTrace();
				} catch (Throwable e) {
					e.printStackTrace();
				}
				return null;
			}

		});
        
        try {
            engine.run("sessionDestroyed.groovy", binding);
        } catch (ResourceException e) {
            e.printStackTrace();
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch(Throwable e){
            e.printStackTrace();
        }
	}

}
